using MauiApp.ViewModels;
using MauiApp.Models;
using Microsoft.Maui.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using MauiApp.Services;
using CommunityToolkit.Mvvm.Input;

namespace MauiApp.Views
{
    public partial class MainPage : ContentPage
    {
        private MainViewModel viewModel;

        public MainPage()
        {
            InitializeComponent();
            // 显式创建MainViewModel实例并设置为BindingContext
            viewModel = new MainViewModel();
            BindingContext = viewModel;
            LogHelper.Debug("MainPage: 构造函数执行完成，ViewModel已创建并设置为BindingContext");
            
            // 订阅CollectionView的事件，检查数据绑定
            if (viewModel != null && viewModel.CurrentFileTime != null)
            {
                viewModel.CurrentFileTime.CollectionChanged += CurrentFileTime_CollectionChanged;
                LogHelper.Debug("MainPage: 已订阅CurrentFileTime的CollectionChanged事件");
            }
        }

        private void CurrentFileTime_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            LogHelper.Debug($"MainPage: CurrentFileTime集合发生变化 - 操作类型: {e.Action}, 新项数: {e.NewItems?.Count ?? 0}, 旧项数: {e.OldItems?.Count ?? 0}");
        }

        protected override async void OnAppearing()
        {
            base.OnAppearing();
            if (viewModel != null)
            {
                LogHelper.Debug("MainPage: OnAppearing调用InitializeAsync");
                await viewModel.InitializeAsync();
                
                // 添加调试输出，检查CurrentFileTime集合是否有数据
                if (viewModel.CurrentFileTime != null)
                {
                    LogHelper.Debug($"MainPage: CurrentFileTime集合数据量: {viewModel.CurrentFileTime.Count}");
                    int count = viewModel.GetCurrentFileCount();
                    LogHelper.Debug($"MainPage: 通过ViewModel方法获取的文件数量: {count}");
                    
                    // 添加一些测试数据，如果集合为空
                    if (viewModel.CurrentFileTime.Count == 0)
                    {
                        LogHelper.Debug("MainPage: 集合为空，添加测试数据...");
                        
                        LogHelper.Debug("MainPage: 已添加测试数据");
                    }
                }
                else
                {
                    LogHelper.Error("MainPage: CurrentFileTime为null");
                }
            }
            else
            {
                LogHelper.Error("MainPage: viewModel为null，无法初始化数据");
            }
        }

        /// <summary>
        /// 点击“打开”按钮的后备调试事件，用于确认点击有无被触发，并直接调用VM命令
        /// </summary>
        private async void OnOpenClicked(object sender, EventArgs e)
        {
            try
            {
                var btn = sender as Button;
                var item = btn?.BindingContext as TimeStampModel;
                LogHelper.Debug($"MainPage.OnOpenClicked 触发。BindingContextType={item?.GetType().FullName ?? "null"}, FileID={item?.FileID}");

                if (item == null)
                {
                    await DisplayAlert("调试", "未获取到列表项数据（BindingContext为空）", "确定");
                    return;
                }

                if (viewModel == null)
                {
                    await DisplayAlert("调试", "ViewModel 为空", "确定");
                    return;
                }

                // 优先通过命令触发（与XAML一致）
                if (viewModel.OpenFileCommand is IAsyncRelayCommand asyncCmd)
                {
                    await asyncCmd.ExecuteAsync(item.FileID);
                }
                else
                {
                    // 直接调用方法（参数为object，int会自动装箱）
                    await viewModel.OpenFile(item.FileID);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"MainPage.OnOpenClicked 异常: {ex.Message}");
                await DisplayAlert("错误", $"点击打开时出错: {ex.Message}", "确定");
            }
        }

        /// <summary>
        /// 提供给CommandParameter绑定的属性
        /// </summary>
        public object CommandParameter => FileTypePicker?.SelectedItem;
    }
}
